package com.invest.utils.httpclient;

import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.util.concurrent.TimeUnit;

/**
 * Created by evan on 2016/6/9.
 */
public class ServiceBuilder {
    private static RequestInterceptor interceptor ;
    static{

        final CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);
        interceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                for (HttpCookie cookie : cookieManager.getCookieStore().getCookies()) {
                    request.addHeader("Cookie", cookie.getValue());
                }
            }
        };

    }

    public static  <E> E buildService(String uri,Class<E> cls){

        try{
            OkHttpClient client = new OkHttpClient();
            client.setReadTimeout(10000L, TimeUnit.MILLISECONDS);
            client.setConnectTimeout(1500L, TimeUnit.MILLISECONDS);
            RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(uri)
                    .setClient(new OkClient(client)) .setErrorHandler(new RetrofitErrorHandler()).setRequestInterceptor(interceptor) .build();
            E service = restAdapter.create(cls);
            return service;

        }catch(Exception e){
            throw new RuntimeException(e);
        }

    }
}
